<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>客服中心</span>
      </div>

      <el-tabs v-model="activeTab">
        <!-- 常见问题 -->
        <el-tab-pane label="常见问题" name="faq">
          <el-collapse v-model="activeFaq">
            <el-collapse-item
              v-for="(item, index) in faqList"
              :key="index"
              :title="item.question"
              :name="index">
              <div>{{ item.answer }}</div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>

        <!-- 在线客服 -->
        <el-tab-pane label="在线客服" name="online">
          <div class="chat-container">
            <div class="chat-messages" ref="messageContainer">
              <div
                v-for="msg in messages"
                :key="msg.id"
                :class="['message', msg.senderType]">
                <div class="message-content">{{ msg.content }}</div>
                <div class="message-time">{{ formatTime(msg.createTime) }}</div>
              </div>
            </div>

            <div class="chat-input">
              <el-input
                v-model="newMessage"
                type="textarea"
                :rows="3"
                placeholder="请输入您的问题..."
                @keyup.enter.native="sendMessage"
              ></el-input>
              <el-button
                type="primary"
                @click="sendMessage"
                :loading="sending"
                style="margin-top: 10px">
                发送
              </el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- 联系方式 -->
        <el-tab-pane label="联系方式" name="contact">
          <div class="contact-info">
            <p><i class="el-icon-phone"></i> 客服电话：5099</p>
            <p><i class="el-icon-message"></i> 客服邮箱：service@example.com</p>
            <p><i class="el-icon-time"></i> 服务时间：周一至周五 9:00-18:00</p>
            <p><i class="el-icon-chat-dot-round"></i> 在线客服：点击上方"在线客服"标签</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CustomerService',
  data() {
    return {
      activeTab: 'faq',
      activeFaq: [],
      newMessage: '',
      sending: false,
      messages: [],
      currentPage: 0,
      pageSize: 20,
      loading: false,
      hasMore: true,
      userId: 3, // 当前用户ID
      adminId: 1, // 默认客服ID
      faqList: [
        {
          question: '如何修改个人资料？',
          answer: '您可以在"个人中心 > 基本资料"页面修改您的个人信息。'
        },
        {
          question: '如何重置密码？',
          answer: '在登录页面点击"忘记密码"，按照提示操作即可重置密码。'
        },
        {
          question: '系统使用遇到问题怎么办？',
          answer: '您可以联系在线客服或拨打客服电话获取帮助。'
        }
      ]
    }
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'online') {
        this.loadMessages()
        this.scrollToBottom()
      }
    }
  },
  methods: {
    async loadMessages() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      try {
        const response = await request({
          url: `/api/chat/messages/${this.userId}`,
          method: 'get',
          params: {
            adminId: this.adminId,
            page: this.currentPage,
            size: this.pageSize
          }
        })

        if (response.messages && response.messages.length > 0) {
          this.messages = [...response.messages.reverse(), ...this.messages]
          this.hasMore = response.currentPage < response.totalPages - 1
          this.currentPage++
        } else {
          this.hasMore = false
        }
      } catch (error) {
        console.error('获取消息失败:', error)
        this.$message.error('获取消息失败')
      } finally {
        this.loading = false
      }
    },
    async sendMessage() {
      if (this.newMessage.trim() === '') {
        this.$message.warning('请输入消息内容')
        return
      }

      this.sending = true
      try {
        // 发送用户消息
        const message = {
          userId: this.userId,
          adminId: this.adminId,
          content: this.newMessage,
          senderType: 'user'
        }

        const response = await request({
          url: '/api/chat/send',
          method: 'post',
          data: message
        })

        if (response) {
          this.messages.push(response)
          this.newMessage = ''
          this.scrollToBottom()
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        this.$message.error('发送消息失败')
      } finally {
        this.sending = false
      }
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messageContainer) {
          this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight
        }
      })
    },
    handleScroll(e) {
      const container = this.$refs.messageContainer
      if (container.scrollTop === 0 && this.hasMore) {
        this.loadMessages()
      }
    }
  },
  mounted() {
    if (this.activeTab === 'online') {
      this.loadMessages()
    }
    // 添加滚动事件监听
    if (this.$refs.messageContainer) {
      this.$refs.messageContainer.addEventListener('scroll', this.handleScroll)
    }
  },
  beforeDestroy() {
    // 移除滚动事件监听
    if (this.$refs.messageContainer) {
      this.$refs.messageContainer.removeEventListener('scroll', this.handleScroll)
    }
  }
}
</script>

<style scoped>
.chat-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.chat-messages {
  height: 400px;
  overflow-y: auto;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.message {
  margin-bottom: 15px;
}

.message.user {
  text-align: right;
}

.message.admin {
  text-align: left;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 70%;
  word-break: break-all;
}

.message.user .message-content {
  background-color: #409eff;
  color: white;
}

.message.admin .message-content {
  background-color: #e6e6e6;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.contact-info p {
  margin: 15px 0;
  font-size: 14px;
}

.contact-info i {
  margin-right: 8px;
  color: #409eff;
}

.chat-input {
  margin-top: 15px;
}

.el-button {
  width: 100%;
}
</style>
